<template>
  <div class="register-container row-start">
    <div class="width-14">
        <div class="header">广西制造业企业培优育强服务券</div>
        <div class="sub-header">统一身份认证平台</div>
    </div>
    <div class="width-10 col-center register-form">
        <div class="mb20 color-white tl fs18">您好，欢迎注册!</div>
        <el-form ref="registerForm" :model="form" :rules="rules" label-width="0px" class="width-16">
          <el-form-item prop="mobile">
            <el-input class="mt15" placeholder="请输入手机号" v-model="form.mobile" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input class="mt15" v-model="form.code" placeholder="请输入图形验证码" auto-complete="off">
              <template #append>
                <img @click="getCaptcha" style="cursor: pointer;height:38px" :src="captchaObj?.img"  />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item placeholder="请输入手机验证码" prop="smsCode">
              <el-input class="mt15" v-model="form.smsCode" placeholder="请输入手机验证码" auto-complete="off">
                <template #append>
                  <el-button :disabled="countdown > 0" @click="getSmsCode">{{ countdown > 0 ? `${countdown}秒` : '获取验证码' }}</el-button>
                </template>
              </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="loginLoading" size="small" class="width-24 mt20" style="background:rgb(89,109,244);border:1px solid rgb(89,109,244)" @click="submitForm">立即注册</el-button>
          </el-form-item>
          <p class="login-link mt15">
            已有账号？<a @click="goToLogin">立即登录</a>
          </p>
        </el-form>
    </div>
    <el-dialog title="请输入图形验证码确认" width="400px" :visible.sync="showDialog">
        <el-input v-model="smsCode" placeholder="请输入图形验证码">
          <template #append>
            <img @click="getPhoneCaptcha" style="cursor: pointer;height:38px" :src="phoneCaptchaObj?.img"  />
          </template>
        </el-input>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog = false">取 消</el-button>
          <el-button type="primary" @click="getSmsCode">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
// 引入login 和 regisiter api接口
import { register,getcode,sendSmsCode } from '@/api/homeApi'
import { setToken } from '@/utils/auth'
export default {
  name: 'RegisterPage',
  data() {
    var validateMobile = (rule, value, callback) => {
      var reg = /^1[3-9]\d{9}$/;
      if (value === '') {
        callback(new Error('请输入手机号'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    };
    var validateUsername = (rule, value, callback) => {
      var reg = /^[A-Za-z\u4e00-\u9fa5][A-Za-z0-9\u4e00-\u9fa5_]{1,19}$/;
      if (value === '') {
        callback(new Error('请输入用户名'));
      } else if (!reg.test(value)) {
        callback(new Error('用户名必须以中文或英文字母开头，仅包含中文、英文字母、数字和下划线，总长度2-20位'));
      } else {
        callback();
      }
    };
    var validatePassword = (rule, value, callback) => {
      var reg = /^\S*(?=\S{8})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*?.])\S*$/;
      if (value === '') {
        callback(new Error('请输入密码'));
      } else if (!reg.test(value)) {
        callback(new Error('密码长度8-20位，至少包含1个大写字母，1个小写字母，1个数字和一个特殊符号(!@#$%^&*?.)'));
      } else {
        callback();
      }
    };
  var validateConfirmPassword = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('请再次输入密码'));
    } else if (value !== this.form.password) {
      callback(new Error('两次输入密码不一致!'));
    } else {
      callback();
    }
  };
    return {
      captchaObj: {
        img: '',
        uuid: ''
      },
      phoneCaptchaObj: {
        img: '',
        uuid: ''
      },
      smsCode: '',
      form: {
        mobile: '',
        code: '',
        smsCode: null
      },
      rules: {
        mobile: [{ validator: validateMobile,  trigger: 'blur' }],
        code: [{ required: true, message: '请输入图形验证码', trigger: 'blur' }],
        smsCode: [{ required: true, message: '请输入手机号验证码', trigger: 'blur' }],
      },
      showDialog: false,
      loginLoading: false,
      confirmLoading: false,
      countdown: 0
    };
  },
  mounted() {
    this.getCaptcha();
  },
  methods: {
    checkPhoneBeforeGetCode() {
      this.$refs.registerForm.validateField('mobile', valid => {
        if (!valid) {
          this.showDialog = true;
          this.getPhoneCaptcha()
        }
      });
    },
    getPhoneCaptcha() {
      getcode().then(res => {
        this.phoneCaptchaObj.img = 'data:image/png;base64,' + res.img;
        this.phoneCaptchaObj.uuid = res.uuid;
      });
    },
    getSmsCode() {
      sendSmsCode({mobile:this.form.mobile,scene:1,code:this.smsCode,uuid:this.phoneCaptchaObj.uuid}).then(res => {
        if (res.code === 200) {
          this.$message.success('验证码发送成功！');
          this.showDialog = false;
          this.countdown = 60;
          const timer = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(timer);
            }
          }, 1000);
        }
      });
    },
    getCaptcha() {
      getcode().then(res => {
        this.captchaObj.img = 'data:image/png;base64,' + res.img;
        this.captchaObj.uuid = res.uuid;
      });
    },
    submitForm() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          console.log('表单验证成功！');
          this.form.uuid = this.captchaObj.uuid;
          register(this.form).then(res => {
            if (res.code === 200) {
              this.$message.success('注册成功！');
              setToken(res.data.access_token);
              this.$router.push({ name: '个人中心' });
            } else {
               this.getCaptcha();
             }
          });
        } else {
          console.log('表单验证失败！');
        }
      });
    },
    goToLogin() {
      this.$router.push({ path: '/login' });
    },
    gotoHome(){
      this.$router.push({ path: '/' });
    }
  }
}
</script>

<style scoped>
/deep/.register-form .el-form-item {
  margin-bottom: 30px;
}
.register-container {
  background-image: url('@/assets/image/login_bg.png');
  height: 100vh;
  background-size: cover;
  position:relative;
}

.logo img {
  margin-left: 30px;
  margin-top: 30px;
}

.header {
  color: white;
  font-weight: bold;
  font-family: 'Microsoft YaHei';
  font-size: 50px;
  margin-bottom: 20px;
  margin-left: 220px;
  margin-top: 220px;
}
.sub-header {
  color: #436AF7;
  font-weight: bold;
  font-family: 'Microsoft YaHei';
  font-size: 30px;
  margin-top: 20px;
  margin-left: 220px;
}

.register-form {
  background: rgba(5,31,84, 0.75);
  border-radius: 8px;
  padding: 0 50px;
}

.el-form-item {
  margin-bottom: 15px;
}

.login-link {
  text-align: center;
  color: white;
}

.login-link a {
  color: #add8e6;
  cursor: pointer;
}
</style>
